<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="search-input" placeholder="输入城市名或拼音" />
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li
          class="search-item"
          v-for="item of list"
          :key="item.id"
          @click="handleCityClick(item.name)"
         >
          {{item.name}}
        </li>
        <li class="search-item" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default({
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      list: []
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search, {
      click: true
    })
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let key in this.cities) {
          this.cities[key].forEach((item) => {
            if (item.spell.indexOf(this.keyword) !== -1 || item.name.indexOf(this.keyword) !== -1) {
              result.push(item)
            }
          })
        }
        this.list = result
        this.timer = null
      })
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  }
})
</script>

<style lang="stylus" scoped>
@import '~styles/variable.styl'
  .search
    background-color: $bgColor
    padding: .1rem
    box-sizing: border-box
    .search-input
      width: 100%
      height: .6rem
      border-radius: .05rem
      text-align: center
      font-size: .22rem
      color: #676766
  .search-content
    position: absolute
    top: 1.5rem
    left: 0
    right: 0
    bottom: 0
    background: #f7f7f7
    overflow: hidden
    z-index: 1
    .search-item
      font-size: .28rem
      line-height: .5rem
      padding-left: .2rem
      background: #fff
      margin-bottom: 1px
</style>
